package com.myopen.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.myopen.kit.UUIDKit;

public class DicType extends Model<DicType>{

	private static final long serialVersionUID = -6951939514385913690L;
	public static final DicType dao = new DicType();
	
	public DicType save(DicType vo,Record currUser) {
		DicType bo=null;
		if(StrKit.isBlank(vo.getStr("id"))){
			bo=new DicType();
			
			bo.set("id", UUIDKit.getUUID());
			bo.set("removed", "0");
			bo.set("createTime", new Date());
			bo.set("updateTime", new Date());
			bo.set("creator", currUser.getStr("id"));
			bo.set("updator", currUser.getStr("id"));
			bo.set("name", vo.getStr("name"));
			bo.set("code", vo.getStr("code"));
			
			bo.save();
		}else{
			bo=DicType.dao.findById(vo.getStr("id"));
			
			bo.set("creator", currUser.getStr("id"));
			bo.set("updator", currUser.getStr("id"));
			bo.set("name", vo.getStr("name"));
			bo.set("code", vo.getStr("code"));

			bo.update();
		}
		
		return bo;
	}
	
	public List<Record> getAllDicType(){
		String sqlDicType="select * from t_dic_type t where t.removed='0' order by t.createTime";
		return Db.find(sqlDicType);
	}
	
	public List<Record> getAllDicTypeAndDicInfo(){
		String sqlDicType="select * from t_dic_type t where t.removed='0' order by t.createTime";
		String sqlDicInfo="select * from t_dic_info t where t.removed='0' order by t.px";
		List<Record> dicTypes=Db.find(sqlDicType);
		List<Record> dicInfos=Db.find(sqlDicInfo);
		for (Record dicType : dicTypes) {
			List<Record> infos=new ArrayList<>();
			for (Record dicInfo : dicInfos) {
				if(dicType.getStr("id").equals(dicInfo.getStr("dicTypeId"))) {
					infos.add(dicInfo);
				}
			}
			dicType.set("dicInfos", infos);
		}
		return dicTypes;
	}
	
	public DicType remove(String id,Record currUser) {
		DicType bo=DicType.dao.findById(id);
		bo.set("removed", "1");
		bo.set("updateTime", new Date());
		bo.set("updator", currUser.getStr("id"));
		bo.update();
		return bo;
	}
}
